#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：HiflyVideoAPI_Test 
@File    ：utils.py.py
@Author  ：beibei
@Date    ：2025/6/10 4:01 PM 
'''
# common/utils.py
import json
from pathlib import Path
from common.caseOutput import info
import random
import os
from business.voices.vo import BusinessRe

from common.yamlLoader import YamlRead


def get_project_root():
    """
    获取项目根目录：
    - 优先使用环境变量 PROJECT_ROOT
    - 否则向上查找包含 requirements.txt 且有 common 或 testCase 目录的目录作为根路径
    """
    env_root = os.environ.get("PROJECT_ROOT")
    if env_root and Path(env_root).exists():
        return Path(env_root)

    current = Path(__file__).resolve()
    for parent in current.parents:
        if (parent / "requirements.txt").exists() and (
            (parent / "common").is_dir() or (parent / "testCase").is_dir()
        ):
            return parent

    raise RuntimeError("❌ 未找到项目根目录，请检查目录结构或设置环境变量 PROJECT_ROOT")


def save_json_response(data, relative_path: str):
    """
    保存 JSON 响应数据到指定项目内路径
    :param data: 要保存的数据
    :param relative_path: 相对项目根目录的路径，如 "data/response/voice/xxx.json"
    """
    info(f"项目相对路径：{relative_path}")
    root = get_project_root()
    output_path = root / relative_path
    output_path.parent.mkdir(parents=True, exist_ok=True)

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    info(f"✅ 响应内容已保存至: {output_path}")


def extract_voice_by_type_v2(path="data/response/voice/voice_list_v2.json", types=(8, 9, 10, 20)):
    """
    提取 voice_list_v2.json 中指定类型的 voice 列表
    :return: dict 如 {8: [...], 10: [...]}
    """
    root = get_project_root()
    file_path = root / path
    with open(file_path, "r", encoding="utf-8") as f:
        content = json.load(f)

    result = {}
    for item in content.get("data", []):
        t = item.get("type")
        v = item.get("voice")
        if t in types:
            result.setdefault(t, []).append(v)
    return result


def extract_voice_by_type_v1(path="data/response/voice/v1/voice_list_v1.json", types=(8, 9, 10, 20,22)):
    """
    提取 voice_list_v1.json 中指定类型的 voice 列表
    :return: dict 如 {8: [...], 10: [...]}
    """
    root = get_project_root()
    file_path = root / path
    with open(file_path, "r", encoding="utf-8") as f:
        content = json.load(f)

    result = {}
    for item in content.get("data", []):
        t = item.get("type")
        v = item.get("voice_id")
        if t in types:
            result.setdefault(t, []).append(v)
    return result

def extract_voice_by_type_v2_22(path="data/response/voice/v2/type_22_voice_list.json", types=(8, 9, 10, 20, 22)):
    root = get_project_root()
    file_path = root / path
    with open(file_path, "r", encoding="utf-8") as f:
        content = json.load(f)

    result = {}
    # 找到所有 *_list 的 key（比如 type_22_list）
    for key, value in content.items():
        if key.endswith("_list") and isinstance(value, list):
            for item in value:
                t = item.get("type")
                v = item.get("voice")
                if t in types:
                    result.setdefault(t, []).append(v)
    return result



def get_random_voice_by_type_v2(t: int):
    """
    随机获取 voice_list_v2 中指定 type 的一个 voice
    """
    voice_dict = extract_voice_by_type_v2(types=(t,))
    voice_list = voice_dict.get(t)
    if not voice_list:
        raise ValueError(f"❌ voice_list.json 中没有 type={t} 的 voice")
    return random.choice(voice_list)


def get_random_avatar_v2(path="data/response/avatar/avatar_list_v2.json"):
    """
    从 avatar_list_v2.json 中随机选取一个 avatar
    """
    root = get_project_root()
    full_path = root / path
    with open(full_path, "r", encoding="utf-8") as f:
        content = json.load(f)

    avatars = [item["avatar"] for item in content.get("data", []) if "avatar" in item]
    if not avatars:
        raise ValueError("avatar_list.json 中无可用 avatar 数据")

    return random.choice(avatars)


def get_random_template_id():
    """
    根据当前环境返回一个随机的模板ID
    """
    env = os.getenv("TEST_ENV", "Offline")

    if env == "Online":
        templates = [
            "KHLXGJ7nSWAb4PjNJcK_aA", "jousPL1eDhdfEmcs185j-A",
            "Xr2LGJCCpZROY1I4LC7qFw", "ifDaOwHcXH9U4-z7_oHVfw",
            "P3ZLBlTAxEsQTPlFtzUP-w", "HaD6zjlh4iRffLgJQx866g",
            "0qjolkR_Zl4tdAB-RKgEnw", "swvtHoKHl6zCxT-sWg4uYg"
        ]
    else:
        templates = [
            "DH78gvpnKYhTmLOveMUU9w", "eh1PGHJCPJEkwnnQM3oyYg",
            "6OfVb2riidelcGs6mlPvaw", "YBdCEZT2Lqxgmy-28Nj6KA",
            "O2Qh8GLd3sAUWwgQWCY5xg", "mChMN5ccDYyC4iPyJFrN3Q",
            "OVsk42OpLw92pHE7FAJsYg", "b-Hm4AhejMovbZ2Dnozn2w"
        ]

    return random.choice(templates)


def get_common_env():
    """
    获取 host、authorization、br 等通用环境信息
    """
    env_config = YamlRead().env_config1()
    host = env_config['host']
    authorization = env_config['Authorization']
    br = BusinessRe()
    return {
        "host": host,
        "authorization": authorization,
        "br": br
    }


